﻿using GetData.webProductClass;
using jutehui.GetData;
using jutehui.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace GetData
{
    public class walatao
    {
        /// <summary>
        /// 瓦拉淘 HTML信息 获取商品信息 并保存到数据库
        /// </summary>
        /// <returns></returns>
        public string GetSaleURL(string url)
        {
            var htmlText = CustomMethod.GetWebHTML(url);
            var productList = GetProductByRegexToHtml(htmlText);
            if (productList == null || productList.Count < 1)
            {
                return "网络异常，未能获取数据";
            }
            // GetProductList(jsonStr, productList);//得到要插入数据库的数据
            //保存数据库
            DataTable dt = null;
            //转化成table插入
            string errorMsg = "";
            dt = CustomMethod.ListToDataTable<Product>(productList, "Product", ref errorMsg);
            if (dt == null || dt.Rows.Count < 1)
            {
                return errorMsg;
            }
            jutehui.BLL.Product bll = new jutehui.BLL.Product();
            string msg = "";

            if (bll.SaveTableData("Product", dt, out msg))
            {
                return "";
            }
            else //返回失败信息
            {
                CustomMethod.WriteLog("瓦拉淘：" + msg);
                return msg;
            }
        }
        /// <summary>
        /// 根据正则解析商品信息
        /// </summary>
        /// <param name="htmlText"></param>
        /// <returns></returns>
        private List<Product> GetProductByRegexToHtml(string htmlText)
        {
            List<Product> pList = new List<Product>();
            ProductTypeEnum pEnum = new ProductTypeEnum();
            string productRegex = @"<li class=""offcode clearfix show"">[\s\S]*?</li>";
            var list = CustomMethod.GetInfoByRegex(productRegex, htmlText, 0);
            if (list == null || list.Count < 1)
            {
                string msg = "瓦拉淘：GetProductByRegex ，没有抓到匹配的商品，检查匹配规则。";
                CustomMethod.WriteLog(msg);
                return null;
            }
            //每个商品匹配所有相关属性并赋值
            for (int index = 0; index < list.Count; index++)
            {
                Product product = new Product();
                product.FromWeb = "瓦拉淘";
                product.TypeId = (int)MallsEnumClass.NavigationType.海淘;
                try
                {
                    var herfList = CustomMethod.GetInfoFroma(list[index]);
                    if (herfList == null || herfList.Count < 2)
                    {
                        CustomMethod.WriteLog("瓦拉淘：没有获取到herf连接数据");
                        continue;
                    }
                    product.Pname = herfList[1];
                    string detailUrl = herfList[0];
                    if(detailUrl=="http://hui.walatao.com/")
                    {
                        continue;
                    }
                    //描述 详细
                    string detailText = CustomMethod.GetHtmlByHttpHelper(detailUrl);
                    //---------------------------------获取商品分类---------------------------------------------
                    string regex = @"<div class=""crumbs"">[\s\S]*?</div>";
                    product.ProductTypeId = pEnum.GetProductTypeId(detailText, regex, typeof(ProductTypeEnum.walataoType), 0);
                    //------------------------------------------------------------------------------------------
                    string desRegex = @"<div class=""description"">[\s\S]*?<h2 class=""title"">";
                    var desContent = CustomMethod.GetInfoByRegex(desRegex, detailText, 0);
                    if (desContent == null || desContent.Count < 1)
                    {
                        product.Description = product.Pname;
                    }
                    else
                    {
                        //获取描述及详细图片
                        string despRegex = @"<p>[\s\S]*?</p>";
                        var desList = CustomMethod.GetInfoByRegex(despRegex, desContent[0], 0);
                        string description = "";
                        if (desList == null || desList.Count < 1)
                        {
                            product.Description = product.Pname;
                        }
                        for (int count = 0; count < desList.Count; count++)
                        {
                            description += Regex.Replace(desList[count], @"<(.[^>]*)>", "") + "|||";

                        }
                        product.Description = description;
                    }
                    //图片链接
                    string srcRegex = @"src=[""|']([^""|']*)[""|']";
                    var detailImg = CustomMethod.GetInfoByRegex(srcRegex, desContent[0], 1);

                    if (detailImg != null && detailImg.Count > 0)
                    {
                        if (detailImg.Count == 1)
                        {
                            product.ImgUrl2 = detailImg[0];
                        }
                        else if (detailImg.Count == 2)
                        {
                            product.ImgUrl2 = detailImg[0];
                            product.ImgUrl3 = detailImg[1];

                        }
                        else
                        {
                            product.ImgUrl2 = detailImg[0];
                            product.ImgUrl3 = detailImg[1];
                            product.ImgUrl4 = detailImg[2];
                        }
                    }
                    //链接
                    List<string> buyList = new List<string>();
                    Regex reg = new Regex(@"(?is)<a[^>]*?data-link=(['""]?)(?<url>[^'""\s>]+)\1[^>]*>(?<text>(?:(?!</?a\b).)*)</a>");
                    MatchCollection mc = reg.Matches(list[index]);
                    foreach (Match m in mc)
                    {
                        buyList.Add(m.Groups["url"].Value);
                        buyList.Add(m.Groups["text"].Value);
                    }
                    if (buyList == null || buyList.Count < 1)
                    {
                        CustomMethod.WriteLog("瓦拉淘：没有获取到商品链接");
                        continue;
                    }
                    string productUrl = "";
                    product.Plink = MallsEnumClass.GetSourceUrl(buyList[0], ref productUrl);

                    if (product.Plink == "")
                    {
                        if (productUrl == "")
                        {
                            CustomMethod.WriteLog("瓦拉淘：没有获取到商品链接");
                        }
                        continue;
                    }
                    product.Memo = productUrl;
                    product.ImgUrl = CustomMethod.GetImgUrl(list[index], "瓦拉淘");
                    if (product.ImgUrl == "")
                    {
                        CustomMethod.WriteLog("瓦拉淘：没有获取到图片链接");
                        continue;
                    }
                    string priceSourceRegex = @"<div class=""right-info fl clearfix"">[\s\S]*?</div>";
                    var pricContent = CustomMethod.GetInfoByRegex(priceSourceRegex, list[index], 0);
                    if (pricContent != null && pricContent.Count > 0)
                    {
                        var priceList = CustomMethod.GetInfoFroma(pricContent[0]);
                        if (priceList == null || priceList.Count < 1)
                        {
                            product.Price = "";
                        }
                        else if (priceList.Count == 2)
                        {
                            product.Price = priceList[1];
                        }
                        else
                        {
                            product.PriceType = priceList[1];
                            product.Price = priceList[3];
                        }
                        //来源
                        var sourContent = CustomMethod.GetInfoFroma(pricContent[0]);
                        if (sourContent.Count > 3)
                        {
                            if (sourContent[sourContent.Count - 1].Contains("直邮"))
                            {
                                product.Source = sourContent[sourContent.Count - 3];
                            }
                            else
                            {
                                product.Source = sourContent[sourContent.Count - 1];
                            }
                        }
                        //string souRegex = @"</label><label>(.*?)</label>";
                        //var sourceList = CustomMethod.GetInfoByRegex(souRegex, pricContent[0], 1);
                        //if (sourceList == null || sourceList.Count < 1)
                        //{
                        //    string cont = @"<dt class=""clearfix"">[\s\S]*?</dt>";
                        //    var sourContent = CustomMethod.GetInfoByRegex(cont, detailText, 0);

                        //    if (sourContent.Count < 1)
                        //    {
                        //        product.Source = "";
                        //    }
                        //    else
                        //    {
                        //        string sourRegex = @"<span class=""fl"">(.*?)</span>";
                        //        var lastSource = CustomMethod.GetInfoByRegex(sourRegex, sourContent[0], 1);
                        //        if (lastSource.Count > 0)
                        //        {
                        //            product.Source = lastSource[0];
                        //        }
                        //        else
                        //        {
                        //            product.Source = "";
                        //        }
                        //    }
                        //}
                        //else
                        //{
                        //    product.Source = sourceList[0];
                        //}

                    }
                    else
                    {
                        product.Source = "";
                        product.Price = "";
                    }

                    product.UpdateTime = DateTime.Now;
                    product.UpdateTimeStr = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    product.Pname = product.Pname.Replace("&#x2F;", "/").Replace("#039;", "'").Replace("&amp;", "&").Replace("&quot;", "\""); 
                    product.Description.Replace("&#x2F;", "/").Replace("#039;", "'");
                    pList.Add(product);
                }
                catch (Exception ex)
                {
                    CustomMethod.WriteLog("瓦拉淘" + ex.Message.ToString());
                    continue;
                }
            }
            var newList = CustomMethod.GetDistinctProdcuts(pList);
            newList.Reverse();
            return newList;
        }
    }
}
